package control;
import java.sql.*;
import java.util.*;
import javax.swing.JCheckBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import model.Student;
public class studentDAO {
	public Connection con;
	public studentDAO(){
		String dbUrl = "jdbc:mysql://localhost:3306/ftico";
		String dbClass = "com.mysql.jdbc.Driver";
		try{
			Class.forName(dbClass);
			con= DriverManager.getConnection(dbUrl, 
			"root", "");
		}catch(Exception e) {
			e.printStackTrace();
		}
	
	}
	public void loadDB(JTable tb){
		String query = "select*from students";
		DefaultTableModel m=new DefaultTableModel();
		tb.setModel(m);
                m.addColumn("ID");m.addColumn("Name");m.addColumn("Sex");m.addColumn("Age");m.addColumn("HomeTown");
		try{ 
			Statement stmt= con.createStatement();
			ResultSet rs= stmt.executeQuery(query);
			while(rs.next()) {
                                JCheckBox c=new JCheckBox();
				m.addRow(new String[]{rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5)});
//                                m.addRow(c);
			} 
			}catch(SQLException e) {
			e.printStackTrace();
			}
		
        
	}
        public void deleteDB(JTable tb){
            for(int i=0;i<tb.getSelectedRowCount();i++){
                int tmp=Integer.parseInt(tb.getValueAt(i, 0).toString());
                String query = "delete from students where id = "+tmp+"";
//                System.out.println(tmp);
                try{ 
                    Statement stmt= con.createStatement();
                    int rs= stmt.executeUpdate(query);
//                    ResultSet rs = stmt.executeUpdate(query);
                    }catch(SQLException e) {
                    e.printStackTrace();
                }
            }
            
        }
        public void addUser(Student per){
		String sql = "INSERT INTO students(id, name, sex, age, homeTown) VALUES(?,?,?,?,?)";
		try{
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setInt(1, 2);
		ps.setString(2,"Phuong");
		ps.setInt(4,21);
		ps.setString(3,"Male");
		ps.setString(5, "Ha Nam");
		ps.executeUpdate();
		}catch(Exception e){
		e.printStackTrace();
		}
	}
}
